package com.example.client.filter;

import com.alibaba.fastjson2.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.client.Utiles.JWTUtiles;
import com.example.client.pojo.Code;
import com.example.client.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JWTTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        Result result = new Result<>();
        String token = request.getHeader("Authorization");
        if (token == null) {
            filterChain.doFilter(request, response);
            return;
        }
        try {
            DecodedJWT decodedJWT = JWTUtiles.vertifyForData(token);
            String username = decodedJWT.getClaim("username").asString();
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);


            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                    new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            filterChain.doFilter(request, response);
            return;
        }
        catch (SignatureVerificationException e) {
            e.printStackTrace();
            result.setMsg("无效的令牌");
        }
        catch (TokenExpiredException e) {
            e.printStackTrace();
            result.setMsg("令牌过期");
        }
        catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            result.setMsg("算法不一致");
        }
        catch (Exception e) {
            e.printStackTrace();
            result.setMsg("令牌无效");
        }
        result.setCode(Code.RESPONSE_CODE_FAIL);
        String jsonString = JSON.toJSONString(result);

        response.setCharacterEncoding("utf-8");
        response.getWriter().println(jsonString);
    }
}
